#!/usr/bin/env python """ Example of an embedded PTK in a custom/pure python main loop """ import time #just to pretend to do some work import __main__ #for engine userdict #i'll fix this import in the next release # from ptk_lib.engine import Engine from ptk_lib.engine import engine, eng_misc #simple global exit flag EXIT = False #main loop function def mainloop(eng): print 'Starting mainloop' while EXIT is False: #do other tasks time.sleep(0.1) #check for engine code eng.process_cmds() print 'Exited mainloop' #engine subclass class MyEngine(engine.Engine): def __init__(self, englabel='MyApp', userdict={}, timeout=10): engine.Engine.__init__(self, englabel, userdict, timeout) # compiled user commands are stored as a code object when recieved and # ran in the mainloop by calling MyEngine.process_cmds() self._code = None def process_cmds(self): """ Process any waiting user commands. """ if self._code is not None: #run code self._run_code(self._code) self._code = None return #---overload base methods--------------------------------------------------- # run code will be called from the comms thread when a user command is # recieved - hence this should raise an event to run the code in the main # thread overwise the comms thread will hang until the command completes! def run_code(self,code): """ Run some compiled code as the user. """ #have a code object so store it and set event self._code=code def exit(self): """ Called when the a System exit is raised in running code """ global EXIT #call the node/client disconnect method to close the node properly. engine.Engine.exit(self) print 'System exit raised by user from PTK console, exiting...' EXIT = True #using a global # called when the engine node disconnects from the message bus - you can do # any actions you want here (report to the user etc) def on_disconnect(self): """ The engine node disconnected from the message bus. This will wake the main loop. """ engine.Engine.on_disconnect(self) print 'Engine disconnected normally from PTK instance - console closed? or disconnect() called' def on_err_disconnect(self): """ The engine node disconnected from the message bus. This will wake the main loop. """ engine.Engine.on_err_disconnect(self) print 'Engine disconnected in error from PTK instance - PTK crashed/killed or an error' # a custom welcome message to be displayed in the console. def get_welcome(self): """Return the engines welcome message""" welcome = engine.Engine.get_welcome(self) + "\n\nRunning embedded in a custom python mainloop\n" return welcome #------------------------------------------------------------------------------- if __name__=='__main__': #create engine and connect to PTK eng = MyEngine(userdict=__main__.__dict__) host = 'localhost' port = eng_misc.get_message_port() eng.connect( host, port ) #start main loop mainloop(eng) eng.shutdown()